#include "leaveapprovedwidget.h"
#include "ui_leaveapprovedwidget.h"
#include "loginwidget.h"
#include <QSqlQuery>
#include <QMessageBox>

LeaveApprovedWidget::LeaveApprovedWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LeaveApprovedWidget)
{
    ui->setupUi(this);
    initWindow();
    initTable();
}

LeaveApprovedWidget::~LeaveApprovedWidget()
{
    delete ui;
}

/**
 * @brief 初始化窗体
 */
void LeaveApprovedWidget::initWindow()
{
    this->setWindowTitle("请假审批");
}

/**
 * @brief 初始化Table
 */
void LeaveApprovedWidget::initTable()
{
    model = new QSqlTableModel(this);
    model->setTable("leave_record"); //指定表
    //model->setFilter(QString("leave_username = %1").arg(LoginWidget::userName));
    model->setFilter("is_approved != '审批通过'");
    model->setHeaderData(1,Qt::Horizontal,"请假人");
    model->setHeaderData(2,Qt::Horizontal,"请假事由");
    model->setHeaderData(3,Qt::Horizontal,"请假起始时间");
    model->setHeaderData(4,Qt::Horizontal,"请假结束时间");
    model->setHeaderData(7,Qt::Horizontal,"审批是否通过");
    model->select(); //查询
    model->setEditStrategy(QSqlTableModel::OnManualSubmit); //Model编辑策略，提交生效
    ui->tableView->setModel(model); //将模型设置到视图中
    ui->tableView->setColumnHidden(0, 1); //隐藏编号列
    ui->tableView->setColumnHidden(5, 1); //隐藏真实结束时间列
    ui->tableView->setColumnHidden(6, 1); //隐藏是否销假列
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);   //使其不可编辑
}

/**
 * @brief 审批通过
 */
void LeaveApprovedWidget::on_btn_pass_clicked()
{
    int curRow = ui->tableView->currentIndex().row(); //获取选中行号
    if (curRow < 0)
    {
        QMessageBox::warning(this, tr("提示"), tr("请先选择要审批的记录"), QMessageBox::Ok);
        return;
    }
    int id = model->itemData(model->index(curRow, 0))[0].toInt();
    QSqlQuery query;
    query.prepare("UPDATE leave_record SET is_approved = '审批通过' WHERE id = :id");
    query.bindValue(":id", id);
    query.exec();
    QMessageBox::information(this, tr("提示"), tr("审批成功"), QMessageBox::Ok);
    initTable();
}

/**
 * @brief 审批不通过
 */
void LeaveApprovedWidget::on_btn_fail_clicked()
{
    int curRow = ui->tableView->currentIndex().row(); //获取选中行号
    int id = model->itemData(model->index(curRow, 0))[0].toInt();
    QSqlQuery query;
    query.prepare("UPDATE leave_record SET is_approved = '审批不通过' WHERE id = :id");
    query.bindValue(":id", id);
    query.exec();
    QMessageBox::information(this, tr("提示"), tr("审批成功"), QMessageBox::Ok);
    initTable();
}
